package cn.thens.kdroid.core.storage

import cn.thens.kdroid.core.io.Codec

internal class CodecStorage<K, V1, V2>(private val storage: Storage<K, V1>, private val codec: Codec<V1, V2>) : Storage<K, V2> {

    override fun node(key: K): Storage.Node<V2> {
        return Node(storage.node(key), codec)
    }

    override fun clear() {
        storage.clear()
    }

    override fun getAll(): Map<K, V2> {
        return storage.getAll().map { Pair(it.key, codec.encode(it.value)) }.toMap()
    }

    override fun getKeys(): Set<K> {
        return storage.getKeys()
    }

    class Node<V1, V2>(private val node: Storage.Node<V1>, private val codec: Codec<V1, V2>) : Storage.Node<V2> {

        override fun get(): V2 {
            return codec.encode(node.get())
        }

        override fun put(value: V2) {
            node.put(codec.decode(value))
        }

        override fun clear() {
            node.clear()
        }

        override fun exists(): Boolean {
            return node.exists()
        }
    }
}
